package com.tuling.netty.splitpacket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;


public class MyServerHandler extends SimpleChannelInboundHandler<MyMessageProtocol> {

    //GlobalEventExecutor.INSTANCE 是全局的事件执行器，是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户加入聊天的信息推送给其它在线的客户端
        System.out.println(ctx.channel().remoteAddress() + " 上线了"+ "\n");

        //创建协议包对象
        String msg = ctx.channel().remoteAddress() + " 上线了"+ "\n";
        MyMessageProtocol messageProtocol = new MyMessageProtocol();
        messageProtocol.setLen(msg.getBytes(CharsetUtil.UTF_8).length);
        messageProtocol.setContent(msg.getBytes(CharsetUtil.UTF_8));
        //该方法会将 channelGroup 中所有的 channel 遍历，并发送消息
        channelGroup.writeAndFlush(messageProtocol);
        channelGroup.add(channel);
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyMessageProtocol msg) throws Exception {
//        System.out.println("====服务端接收到消息如下====");
//        System.out.println("长度=" + msg.getLen());
//        System.out.println("内容=" + new String(msg.getContent(), CharsetUtil.UTF_8));
//
//        System.out.println("服务端接收到消息包数量=" + (++this.count));


        //获取到当前 channel
        Channel channel = ctx.channel();
        //这时我们遍历 channelGroup, 根据不同的情况， 回送不同的消息
        channelGroup.forEach(ch -> {
            String message = "";
            if (channel != ch) { //不是当前的 channel,转发消息
                message = "[ 客户端 ]" + channel.remoteAddress() + " 发送了消息：" + new String(msg.getContent(), CharsetUtil.UTF_8) + "\n" + "_";
            } else {//回显自己发送的消息给自己
                message = "[ 自己 ]发送了消息：" + new String(msg.getContent(), CharsetUtil.UTF_8) + "\n";
            }
            MyMessageProtocol messageProtocol = new MyMessageProtocol();
            messageProtocol.setLen(message.getBytes(CharsetUtil.UTF_8).length);
            messageProtocol.setContent(message.getBytes(CharsetUtil.UTF_8));
            ch.writeAndFlush(messageProtocol);
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
